package me.bemayor.components.twin;

import me.bemayor.BeMayor;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.Chest;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;

import java.util.ArrayList;
import java.util.List;

public class TwinUsage {

    public static void setNameToItem(ItemStack itemStack, String newName) {
        if(newName==null || newName.isEmpty()){
            newName="未命名箱子";
        }
        ItemMeta meta = itemStack.getItemMeta();
        meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', newName+"-"+meta.getDisplayName()));
        itemStack.setItemMeta(meta);
    }
    public static void setLocationToItem(ItemStack itemStack, String locationString) {
        ItemMeta meta = itemStack.getItemMeta();
        List<String> lore = meta.getLore();
        if (lore.size() > 2) {
            lore.set(2, locationString);
            meta.setLore(lore);
            itemStack.setItemMeta(meta);
        }
    }
    public static String getStringFromLocation(Location location) {
        return location.getWorld().getName() + "." +
                location.getBlockX() + "." +
                location.getBlockY() + "." +
                location.getBlockZ();
    }
    public static Location getLocationFromString(String locationString) {
        String[] s = locationString.split("\\.");
        if (s.length >= 4) {
            World w = BeMayor.getPlugin(BeMayor.class).getServer().getWorld(s[0]);
            return new Location(w, Double.valueOf(s[1]), Double.valueOf(s[2]), Double.valueOf(s[3]));
        } else {
            return null;
        }
    }

    public static Chest getChest(Location chestLocation) {
        Block b=chestLocation.getBlock();
        if (b.getType() == Material.CHEST) {
            return (Chest)b.getState();
        } else {
            return null;
        }
    }

    public static Location findChest(Location l) {
        List<Location> list=new ArrayList<>();
        for(int i=0;i<6;i++){
            list.add(l.clone());
        }
        list.get(0).setX(l.getBlockX()-1);
        list.get(1).setX(l.getBlockX()+1);
        list.get(2).setZ(l.getBlockZ()-1);
        list.get(3).setZ(l.getBlockZ()+1);
        list.get(4).setY(l.getBlockY()-1);
        list.get(5).setY(l.getBlockY()+1);
        for(Location loc:list){
            if(loc.getBlock().getType() == Material.CHEST){
                return loc;
            }
        }
        return null;
    }

}
